package microservice

import (
	"encoding/xml"
	"fmt"
	"github.com/vifraa/gopom"
	"os"
	"sigs.k8s.io/yaml"
)

type Serve struct {
	Port uint `json:"port"`
}
type ConfigYaml struct {
	Serve Serve `json:"server"`
}

// Function ParsePomFile is from a string *pom*(such as **/pom.xml ) to generate the gopom.Project ,which have the right struct and convenient way to get infomation
func ParsePomFile(pom string) (gopom.Project, error) {
	_, err := os.Stat(pom)
	if err != nil {
		return gopom.Project{}, fmt.Errorf("wrong pom file path :% s", pom)
	}
	xmlbyte, err := os.ReadFile(pom)
	var pominfo gopom.Project
	xml.Unmarshal(xmlbyte, &pominfo)
	if err != nil {
		return gopom.Project{}, err
	}
	return pominfo, nil

}

// Function ParseYamlFile ,Like the ParsePomFile,is to parse the application.yaml file in some springboot project.
func ParseYamlFile(yamlpath string) (ConfigYaml, error) {
	_, err := os.Stat(yamlpath)
	if err != nil {
		return ConfigYaml{}, fmt.Errorf("wrong config yaml  file path :% s", yamlpath)
	}
	_byte, _ := os.ReadFile(yamlpath)
	var _yaml ConfigYaml

	err = yaml.Unmarshal(_byte, &_yaml)
	if err != nil {
		return ConfigYaml{}, err
	}
	return _yaml, nil
}

// Function GenerateJarPath is used to Genereta the Jar file name of the Given Pom Data sturct parsed
func GenerateJarPath(proj gopom.Project) string {
	return fmt.Sprintf("%s-%s.%s", proj.Name, proj.Version, proj.Packaging)
}
